<template>
  <div>
    <!-- 树形结构 -->
    <el-tree ref="tree" :default-checked-keys="permIdsList" node-key="id" check-strictly :data="permissionList" :props="defaultProps" default-expand-all show-checkbox />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="$emit('cancel')">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissions } from '@/api/permissions'
import { transListToTreeData } from '@/utils'
import { assignPerm, getRoleDetail } from '@/api/role'

export default {
  name: 'AssignPerms',
  props: {
    currentId: {
      type: [String, Number],
      required: true
    }
  },

  data() {
    return {
      permIdsList: [], // 默认选中的节点
      permissionList: [], // 获取的所有权限
      defaultProps: {
        children: 'children', // 表示层级关系的属性名
        label: 'name' // 渲染节点文本的属性名
      }
    }
  },

  created() {
    this.loadAllPermissions()
    this.loadROleDetail()
  },

  methods: {
    // 获取所有的权限
    async loadAllPermissions() {
      try {
        const { data } = await getPermissions()
        this.permissionList = transListToTreeData(data, 0)
      } catch (error) {
        console.log(error)
      }
    },
    // 点击确认发请求
    async hSubmit() {
      try {
        // getCheckedKeys()是el-tree自带的通过key获取选中的权限id
        const permIds = this.$refs.tree.getCheckedKeys()
        const res = await assignPerm({ id: this.currentId, permIds })
        // 提醒用户
        this.$message.success(res.message)
        // 关闭dialog
        this.$emit('cancel')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 做权限点的回填
    async loadROleDetail() {
      try {
        const { data } = await getRoleDetail(this.currentId)
        this.permIdsList = data.permIds
        // 也可以用这种设置key的方法
        // this.$refs.tree.setCheckedKeys(data.permIds)
      // console.log(data.permIds)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
